new Vue({
  el: '#app',
  data: {
    ossImgUrl: ossImgUrl,//oss图片域名
    env: '',//判断环境
    type: 2,//信息类型 1 企业基本信息 2 代办人信息
    isSelf: 1,//type=2时必填 是否是法人 1：是 0：否
    is_agency: 1,//法人代办人 1 法人 2 代办人
    enp_user: "",//姓名
    user_phone: "",//手机号
    user_number: "",//证件号
    user_front_img: "",//证件正面照
    user_verso_img: "",//证件反面照
    bank_name: '',//开户行
    bank_num: '',//开户账号
    email: "",//邮箱
    flag: false,//下一步是否可点击
    isEdit: true,//银行信息（开户行和卡）
    isReadonly: false,//法人手机号可编辑（单独做验证）
  },
  created() {
    // 判断是否在小程序内
    var u = window.navigator.userAgent;
    var that = this;
    if (/MicroMessenger/i.test(u)) {//判断是否是微信环境
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {// 小程序
          that.env = 'mp';
        }
      })
    }
  },
  mounted() {
    this.queryInfo();
  },
  methods: {
    // 切换法人代办人 1 法人 2 代办人
    switchAgency: function (e) {
      this.is_agency = e;
      if (this.is_agency == 1) { //法人
        this.isSelf = 1
      } else if (this.is_agency == 2) {//代办人
        this.isSelf = 0
      }
      this.enp_user = "";
      this.user_phone = "";
      this.user_number = "";
      this.user_front_img = "";
      this.user_verso_img = "";
      this.bank_name = "";
      this.bank_num = "";
      this.email = "";
      this.queryInfo();
      this.mustClick();
    },
    //身份证号验证（必须18位）
    verifyId: function () {
      if (!this.user_number) { return }
      if (this.user_number.length != 18) {
        mui.toast('证件号必须为18位');
        this.user_number = "";
      }
      this.mustClick();
    },
    // 上传照片通用方法
    upLoad: async function (inputName, type) {
      var inputDOM = this.$refs[inputName];
      var file = inputDOM.files[0]
      //判断是否是图片类型
      if (!/image\/\w+/.test(file.type)) {
        mui.toast("只能选择图片");
        return false;
      }
      var base64 = await this.repairPhoto(file, 0.9, 720);
      switch (type) {
        case 4://证件照正面
          this.user_front_img = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.user_front_img = httpImgUrl + url;
          break;
        case 5://证件照反面
          this.user_verso_img = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.user_verso_img = httpImgUrl + url;
          break;
      }
      this.mustClick();
    },
    // 整体调用
    repairPhoto: async function (file, num, w) {
      const result = await this.isNeedFixPhoto(file);
      const resultBase64 = await this.file2Base64(file);
      const Orientation = result.Orientation;
      const numb = num || 1;
      if (result.flag) {// 处理旋转
        return await this.best4Photo(resultBase64, Orientation, numb, w)
      } else { // 不处理旋转
        return await this.best4Photo(resultBase64, 1, numb, w)
      }
    },
    // 压缩处理选中的方法
    best4Photo: function (resultBase64, Orientation, num, w) {
      return new Promise(function (resolve, reject) {
        var image = new Image();
        image.src = resultBase64;
        image.onload = function () {
          var imgWidth = w;
          var imgHeight = w * this.height / this.width; //获取图片宽高
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext('2d');
          canvas.width = imgWidth;
          canvas.height = imgHeight;
          if (Orientation && Orientation != 1) {
            switch (Orientation) {
              case 6:     // 旋转90度
                canvas.width = imgHeight;
                canvas.height = imgWidth;
                ctx.rotate(Math.PI / 2);
                ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
                break;
              case 3:// 旋转180度
                ctx.rotate(Math.PI);
                ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
                break;
              case 8:     // 旋转-90度
                canvas.width = imgHeight;
                canvas.height = imgWidth;
                ctx.rotate(3 * Math.PI / 2);
                ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                break;
            }
          } else {
            ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
          }
          const result = canvas.toDataURL("image/jpeg", num);
          resolve(result)
        }
      })
    },
    // 上传图片到服务器
    uploadHttp: function (base64) {
      var filename = new Date().getTime() + "_" + (Math.random() * 100000).toFixed(0);
      return new Promise(function (resolve, reject) {
        post("api/upload/base64", {
          file: base64,
          filename: filename,
          dirPath: 'credentials'
        }).then(function (res) {
          var url = res.data.url;
          resolve(url)
        })
      })
    },
    // 判断图片是否需要旋转
    isNeedFixPhoto: function (file) {
      return new Promise(function (resolve, reject) {
        EXIF.getData(file, function () {
          var Orientation = EXIF.getTag(this, 'Orientation');
          if (Orientation && Orientation != 1) {
            //图片角度不正确
            resolve({ flag: true, Orientation: Orientation })
          } else {
            //不需处理直接上传
            resolve({ flag: false, Orientation: Orientation })
          }
        })
      })
    },
    // 将file文件 读成base64码 
    file2Base64: function (file) {
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (ev) {
          resolve(ev.target.result);
        }
      })
    },
    // 删除照片通用方法
    deletePic: function (type) {
      if (this.is_agency == 1) {//为企业法人时不可编辑
        return
      }
      switch (type) {
        case 4://证件照正面
          this.user_front_img = "";
          break;
        case 5://证件照反面
          this.user_verso_img = "";
          break;
      }
      this.mustClick();
    },
    //email验证
    emailReg: function () {
      if (!this.email) { return }
      var ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      if (!ePattern.test(this.email)) {
        mui.toast('请输入正确的邮箱');
        this.email = "";
      }
    },
    // 失去焦点验证下一步是否可点击
    mustClick: function () {
      if (!this.is_agency) {
        this.flag = false
      } else if (!this.enp_user) {
        this.flag = false
      } else if (!this.user_phone) {
        this.flag = false
      } else if (!this.user_number) {
        this.flag = false
      } else if (!this.user_front_img) {
        this.flag = false
      } else if (!this.user_verso_img) {
        this.flag = false
      } else if (!this.bank_name) {
        this.flag = false
      } else if (!this.bank_num) {
        this.flag = false
      } else {
        this.flag = true
      }
    },
    // 下一步
    submit: function () {
      var that = this;
      if (!this.flag) {
        return
      }
      post("api/agency/auth", {
        enp_user: this.enp_user.replace(/\s*/g, ""),
        user_number: this.user_number.replace(/\s*/g, ""),
        user_front_img: this.user_front_img.split('/').slice(3).join('/'),//去除域名
        user_verso_img: this.user_verso_img.split('/').slice(3).join('/'),//去除域名
        user_type: 0,
        user_phone: this.user_phone.replace(/\s*/g, ""),
        is_agency: this.is_agency,
        bank_name: this.bank_name,
        bank_num: this.bank_num.replace(/\s*/g, ""),
        email: this.email ? this.email : null
      }).then(function (res) {
        if (res.data) {
          if (that.is_agency == 1) {//法人本人->法人授权书认证-发送页
            window.location.href = "legalRz_fs.html?user_phone=" + removeBlank(that.user_phone);
          } else if (that.is_agency == 2) {// 代办人
            if (res.data.auth_status == 3) {//认证成功->法人授权书认证-发送页
              window.location.href = "legalRz_fs.html?user_phone=" + removeBlank(that.user_phone);
            } else {//->跳填写验证码页
              window.location.href = "short_code.html?flow_id=" + res.data.flow_id + "&user_number=" + removeBlank(that.user_number) + "&user_phone=" + removeBlank(that.user_phone);
            }
          }
        }
      })
    },
    /* 第二次的流程 */
    // 查询签约信息
    queryInfo: function () {
      var that = this;
      get("api/enp/" + this.type + "/user/" + this.isSelf).then(function (res) {
        if (JSON.stringify(res.data) != "{}" && res.data) {//如果有数据将信息填入
          var data = res.data;
          that.isEdit = data.is_edit;
          // that.is_agency = data.is_agency;
          if (data.agency) {
            that.enp_user = data.agency.enp_user;
            that.user_phone = data.agency.user_phone;
            if (that.user_phone && that.is_agency == 1) {//有法人手机号-不可编辑
              that.isReadonly = true;
            } else {//可编辑
              that.isReadonly = false;
            }
            that.user_number = data.agency.user_number;
            that.user_front_img = data.agency.user_front_img ? httpImgUrl + data.agency.user_front_img : '';
            that.user_verso_img = data.agency.user_verso_img ? httpImgUrl + data.agency.user_verso_img : '';
          }
          that.bank_name = data.bank_name;
          that.bank_num = data.bank_num;
          that.email = data.email;
          that.mustClick();//检测下一步按钮是否高亮
        } else { // 是初次注册
          // 不管
        }
      })
    }
  }
})